var router = require('koa-router')()
var db = require('../utils/mysql.js');

router.get('/list',async ctx=>{
  const result = await blogList();
  ctx.body={'err':0,'blogList':result};
})
router.get('/detail/:id',async ctx=> {
  var id =ctx.params.id;
  var sql = "select a.id,a.title,a.content,a.create_id createId,a.create_time createTime,b.show_name userName from blog_publish a left join blog_user b on a.create_id=b.id where a.id=:id";
  const result = await db.query(sql,{id:id});
  if(result.length>0){
    ctx.body ={'err':0,'info':result[0]}
  }
});
router.post('/add',async ctx=> {
	// 新增用户
  const data = ctx.request.body;
  var title = data.title;
  if(!title){
    ctx.body={'err':1,'msg':'标题不能为空'}

     return ;
  }
  var user = JSON.parse(ctx.cookies.get('user')||'{}');
  if(!user || !user.id){
    ctx.body={'err':2,'msg':'请登录','to':'/user/login'}
    return ;
  }
  var sql = "insert into blog_publish(title,content,create_id) values (:title,:content,:createId)";
  const result = await db.query(sql,{title:title,content:data.content,createId:user.id});
  if(result.insertId){
    ctx.body={'err':0}
  }
});
router.get('/', ctx=> {
  ctx.body='respond with a publish';
});

async function blogList(blog={}){
  let sql = "select a.id,a.title,a.content,a.create_id userId,a.create_time createTime,b.show_name userName from blog_publish a left join blog_user b on a.create_id=b.id where 1=1";
  const queryObj = {};
  if(blog.createId){
    sql += " and a.create_id=:createId";
    queryObj.createId = blog.createId;
  }
  return await db.query(sql+" order by a.create_id desc",queryObj);
}

module.exports = router;
